import modelExtend from 'dva-model-extend'
import { lwjPageModel } from 'utils/model'
import { routerRedux } from 'dva/router';

import {
  createLog,
  recharge,
  query,
  accumulated,
  createBillRecord,
  queryTenant,
  filterDistributor
} from './services/financialRecharge';
import { listPaymenters, listDistributors } from './services/financialReceipt';
import { list, shopOverall } from './services/financialAccountBalance';
import { tenantList, createOutlineBillRecord, getTargetMoney, currentTenants } from './services/tenantRelative';
import pathToRegexp from 'path-to-regexp';
import { pay } from './services/financialPaymentBill';
import { Modal } from 'antd';

export default modelExtend(lwjPageModel, {
  namespace: 'recharge',
  state: {
    currentItem: {},
    currentSaleDistributor: '',
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    visible: false,
    rechargeLogId: "",
    rechargePath: "",
    balance: "",
    totalToProfits: "",
    accumulated: "",
    currentType: "",
    thirdAccountId: "",
    shops: [],
    queryParam: {},
    tenant: [],
    visibleTenant: false,
    hasMoney: '',
    currentTenant: '',
    currentTenantId: '',
    currentUrl: "",
    distributors: {},
    offOrOnline: '',
    isCustomize: true
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        const match = pathToRegexp('/financial/:type/charge').exec(pathname);
        if (match) {
          dispatch({ type: 'querySuccess', payload: {} })
          dispatch({ type: 'currentTenant', payload: {} })
          const type = match[1];
          if (type === "shop") {
            dispatch({ type: 'queryShopBalance', payload: {} })

            // dispatch({type: 'getBalance', payload: {}}) dispatch({   type: 'query',
            // payload: {     chargeType: "DISTRIBUTOR_RECHARGE"   } }) dispatch({type:
            // 'listShops'}) dispatch({   type: 'getAccumulated',   payload: { chargeType:
            // "DISTRIBUTOR_RECHARGE"   } })
          }
          if (type === "tenant") {
            dispatch({ type: 'getTargetMoney', payload: {} })
            dispatch({
              type: 'queryTenant',
              payload: {
                chargeType: "TENANT_RECHARGE"
              }
            })
            dispatch({
              type: 'getAccumulated',
              payload: {
                chargeType: "TENANT_RECHARGE"
              }
            })
          }
          dispatch({
            type: 'type',
            payload: {
              currentType: type
            }
          })
        }
      })
    }
  },
  effects: {
    * queryShopBalance({
      payload
    }, { select, call, put, take }) {
      yield put({ type: 'listShops' })
      yield take('listShops/@@end');
      const saleDistributors = yield select(({ recharge }) => recharge.shops);
      if (saleDistributors.length > 0) {
        yield put({
          type: 'filterDistributor',
          payload: {
            distributor: saleDistributors[0]
          }
        })

        // yield put({   type: 'getBalance',   payload: {     distributorId:
        // saleDistributors[0].id   } })
        // yield put({
        //   type: 'getAccumulated',
        //   payload: {
        //     chargeType: "DISTRIBUTOR_RECHARGE",
        //     distributorId: saleDistributors[0].id
        //   }
        // })
        yield put({
          type: 'query',
          payload: {
            chargeType: "DISTRIBUTOR_RECHARGE",
            distributorId: saleDistributors[0].id
          }
        })
      }
    },
    * query({
      payload
    }, { select, call, put }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      });
      const pageOptions = yield select(({ recharge }) => recharge.pageOptions);
      const queryParam = yield select(({ recharge }) => recharge.queryParam);
      delete payload.isTablePagination
      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...queryParam,
          ...payload
        }
      };
      const data = yield call(query, queryPayload);

      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    /**
     * 线下充值相关
     * @param {*} param0
     * @param {*} param1
     */
    * queryTenant({
      payload
    }, { select, call, put }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      });

      const pageOptions = yield select(({ recharge }) => recharge.pageOptions);
      const queryParam = yield select(({ recharge }) => recharge.queryParam);
      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...queryParam
        }
      };
      const data = yield call(query, queryPayload);
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    /**
     * 线下充值列表
     * @param {*} param0
     * @param {*} param1
     */
    * listTenant({
      payload
    }, { select, call, put }) {
      const data = yield call(tenantList);
      yield put({ type: 'setTenant', payload: data.content })
    },
    /**
     * 线下充值创建
     * @param {*} param0
     * @param {*} param1
     */
    * createOutlineBillRecord({
      payload
    }, { select, call, put }) {
      const dataLog = yield call(createOutlineBillRecord, {
        ...payload
      });
      if (dataLog.code === 0) {
        Modal.success({ title: '成功', content: '您已成功添加线下充值记录' })
        yield put({
          type: 'showRechargeTenant',
          payload: {
            visible: false
          }
        });
        yield put({
          type: 'query',
          payload: {
            chargeType: "TENANT_RECHARGE"
          }
        })
        yield put({ type: 'getTargetMoney', payload: {} })
      }
    },
    /**
     * 线下充值金额查询
     * @param {*} param0
     * @param {*} param1
     */
    * getTargetMoney({
      payload
    }, { select, call, put }) {
      const data = yield call(getTargetMoney);
      yield put({
        type: 'saveHasMoney',
        payload: {
          hasMoney: data.result
        }
      })
    },
    /**
     * 获取当前账户
     * @param {*} param0
     * @param {*} param1
     */
    * currentTenant({
      payload
    }, { select, call, put }) {
      const data = yield call(currentTenants);
      yield put({
        type: 'savecurrentTenant',
        payload: {
          currentTenant: data.result.displayName,
          currentTenantId: data.result.id
        }
      })
    },
    /**
     * 租户充值创建充值记录并获取地址
     * @param {} param0
     * @param {*} param1
     */
    * tenantRecharge({
      payload
    }, { select, call, put }) {
      const newWindow = window.open();
      const dataLog = yield call(createLog, {
        amountMoney: payload.amountMoney,
        rechargeMode: payload.rechargeMode,
        payerId: payload.payerId,
        chargeType: payload.chargeType,
        isCustomize: payload.isCustomize
      });
      if (dataLog.code === 0) {
        yield put({
          type: "setRechargeLogId",
          payload: {
            result: dataLog.result
          }
        })
        const dataPath = yield call(recharge, {
          payMoney: payload.payMoney,
          showUrl: payload.showUrl,
          rechargeId: dataLog.result,
          paymentReceiptType: payload.paymentReceiptType
        });
        if (dataPath.code === 0) {
          yield put({
            type: "setRechargePath",
            payload: {
              result: dataPath.result
            }
          })
          newWindow.location.href = dataPath.result
          // window.open(dataPath.result, '_blank');
        }
      }
    },
    /**
     * 门店充值
     * @param {} param0
     * @param {*} param1
     */
    * shopRecharge({
      payload
    }, { select, call, put }) {
      const dataLog = yield call(createBillRecord, {
        ...payload
      });
      if (dataLog.code === 0) {
        Modal.success({ title: '成功', content: '充值成功，请审核' })
        yield put({
          type: 'showRecharge',
          payload: {
            visible: false
          }
        })
      }
    },
    * createRechargePath({
      payload
    }, { select, call, put }) {
      const data = yield call(recharge, payload);
      if (data.code === 0) {
        yield put({
          type: "setRechargePath",
          payload: {
            result: data.result
          }
        })
      }
    },
    * getBalance({
      payload
    }, { select, call, put }) {
      const data = yield call(shopOverall);
      yield put({ type: 'setBalance', payload: data })
    },
    * getAccumulated({
      payload
    }, { select, call, put }) {
      // console.info(payload)
      const data = yield call(accumulated, payload);
      yield put({ type: 'setAccumulated', payload: data.result })
    },

    * listShops({
      payload
    }, { select, call, put }) {
      const data = yield call(listDistributors);
      yield put({ type: 'setShops', payload: data.list })
    },
    * filterDistributor({
      payload
    }, { select, call, put }) {
      const data = yield call(filterDistributor, payload);
      yield put({
        type: 'setMoneyByDistributor',
        payload: {
          ...data.result,
          currentSaleDistributor: payload.distributor
        }
      })
    },
    * showBalanceRecords({
      payload
    }, { select, call, put }) {
      yield put(routerRedux.push(`/financialAccountBalanceRecord/${payload}`));
    },
    * initState({
      payload
    }, { select, call, put }) {
      yield put(routerRedux.push(`/financial/shop/charge`));
    }
  },
  reducers: {
    setMoneyByDistributor(state, { payload }) {
      return {
        ...state,
        balance: payload.overall,
        accumulated: payload.rechargeAll,
        totalToProfits: payload.totalToProfits,
        currentSaleDistributor: payload.currentSaleDistributor,
        thirdAccountId: payload.thirdAccountId
      }
    },
    setTenant(state, { payload }) {
      return {
        ...state,
        tenant: payload
      }
    },
    setShops(state, { payload }) {
      return {
        ...state,
        ...payload,
        shops: payload
      }
    },
    showRecharge(state, { payload }) {
      return {
        ...state,
        ...payload,
        visible: payload.visible
      }
    },
    setRechargeLogId(state, { payload }) {
      return {
        ...state,
        ...payload,
        rechargeLogId: payload.result
      }
    },
    setRechargePath(state, { payload }) {
      return {
        ...state,
        ...payload,
        rechargePath: payload.result
      }
    },
    setBalance(state, { payload }) {
      return {
        ...state,
        ...payload,
        balance: payload.result
      }
    },
    setAccumulated(state, { payload }) {
      return {
        ...state,
        ...payload,
        accumulated: payload
      }
    },
    type(state, { payload }) {
      return {
        ...state,
        currentType: payload.currentType
      }
    },
    showRechargeTenant(state, { payload }) {
      return {
        ...state,
        visibleTenant: payload.visible
      }
    },
    saveHasMoney(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    savecurrentTenant(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    setCurrentUrl(state, { payload }) {
      return {
        ...state,
        ...payload,
        currentUrl: payload.currentUrl
      }
    },
    setOffOrOnline(state, { payload }) {
      return {
        ...state,
        ...payload,
        offOrOnline: payload.offOrOnline
      }
    },
    setCustomize(state, { payload }) {
      console.info(payload)
      return {
        ...state,
        ...payload,
        isCustomize: payload.isCustomize
      }
    },
  }
})
